import * as React from 'react';

import { WithSettingDetailHead } from '../../component/WithSettingDetailHead/WithSettingDetailHead';
import TransmitSelectModal from '../../component/transmitSelectModal/TransmitSelectModal';


import { message, Button, TimePicker } from 'antd';
import { Input } from 'antd';
const { TextArea } = Input;

import { SelectItemType, SelectType } from '../../interface/ITransmit';
import webIM from '../../net/WebIM';
import { MessageType } from '../../net/Const';

import chatStore from '../../store/ChatStore';
import Radio from 'antd/es/radio';
import SendBoardSimple from '../../component/sendBoard/SendBoardSimple';
import { MessageItem } from '../../interface/IChat';
// import groupStore from '../../store/GroupStore';
// import friendStore from '../../store/FriendStore';
import './MesGroupSend.less'

export interface IMesGroupSendProps {
  submitTransmit?:()=>void;
  onComplete?:()=>void;
  visible?:boolean
}

export interface IMesGroupSendState {
  msgContent: string,
  showSelectChatModal: boolean;
  sendType:'now'|'time'
  chats: SelectItemType[],
  visible?:boolean,
  isSending?:boolean
}

class MesGroupSend extends React.Component<IMesGroupSendProps, IMesGroupSendState> {

  constructor(props: IMesGroupSendProps) {
    super(props);

    this.state = {
      msgContent: '',
      showSelectChatModal: false,
      sendType:'now',
      chats: [],
      visible:this.props.visible,
      isSending:false,

    }
    this.chatsRef = React.createRef();
  }
  componentDidMount(): void {
    this.setState({
      isSending:false
    })
  }

  chatsRef: any;
  changeMsgContent = ( msg:MessageItem ) => {
    this.setState({
      msgContent: msg.content
    });
  };
  submitTransmit=( chats:SelectItemType[] )=>{
    this.setState({
      chats:chats
    })
  };
  sendToChats = (chats: SelectItemType[]) => {
    if( !chats.length){
      message.error('请选择要发送的好友');
      return;
    }
    if( !this.state.msgContent){
      message.error('请输入要发送的内容');
      return;
    }
    for (let index = 0; index < chats.length; index++) {
      const chat = chats[index];

      let timer = setInterval(() => {
        timer && clearTimeout(timer);
        this.send(chat)
      }, 50);

    }
    this.hideTransmit();
  };

  sendTransmit = () => {
    
    this.sendToChats(this.state.chats);
  };
  hideTransmit = () => {
    if( this.chatsRef && this.chatsRef.current){
      this.chatsRef.current.clear()
    }
    
  };

  send = (_chat: any) => {
    var content = this.state.msgContent
    if (!content) {
      message.warn('不能发送空内容');
      return;
    }
    if( this.state.isSending ){
      message.warn('正在发送');
      return;
    }
    let chat = _chat.data;
    let chatId = "";
    let toUserName = "";
    if (_chat.transmitType == SelectType.chat) {
      chatId = chat.id + '';
      toUserName = chat.name;

    } else if (_chat.transmitType == SelectType.group) {
      chatId = chat.jid + '';
      toUserName = chat.name;
    } else if (_chat.transmitType == SelectType.friend) {
      chatId = chat.toUserId + '';
      toUserName = chat.toNickname;
    }
    console.log(chatId, '-----chatId--------');


    // let chart = chatStore;
    // const chatItem = chart.chats.find(item => item.id == chatId);
    // console.log('发送的消息', chatItem);
    const _msgData = {
      type: MessageType.TEXT,
      content: content,
      toUserId: chatId,
      toUserName: toUserName
    };
    const msg = webIM.createMessage(_msgData.type, _msgData.content, _msgData.toUserId, _msgData.toUserName);

    
    webIM.sendMessage(msg, '');

    // console.log(msg,'发出的消息是什么?????????????',msg.to,msg.toJid,msg.toUserId,msg.toUserName)
    // msg.fromUserName = chart.currentChatData.nickname ? chart.currentChatData.nickname : msg.fromUserName;
    chatStore.addMessage(chatId, msg, true);
    // console.log(this.injected.chatStore.messageData.get(chatId),'消息体里的数据') 
    chatStore.updateMes(content, msg.timeSend, chatId);
    //chatStore.addToChats(chat);
    this.props.onComplete? this.props.onComplete() : '';
    this.setState({
      isSending:false 
    })  
  };

  static getDerivedStateFromProps(nextProps:IMesGroupSendProps, prevState: IMesGroupSendState) {
		const storeProps = nextProps as IMesGroupSendProps
    
		if (nextProps.visible!= prevState.visible ) {
      const newState:any = {
        visible:nextProps.visible
      }
      if( !nextProps.visible ){
        newState.msgContent = ''
      }
			return newState
		}else{
      return null
    }
	}
  public render() {
    return (
      <div style={{ padding:'10px 30px'}} className="mes-group-send">
        <div className="group-send-block">
          <h4>群发内容</h4>
          <SendBoardSimple content={this.state.msgContent} onContentChange={this.changeMsgContent}></SendBoardSimple>
        </div>
        <div className='group-send-block'>
          <h4>选择发送好友</h4>
          <div>
            <TransmitSelectModal ref={this.chatsRef} submitTransmit={this.submitTransmit } />
          </div>
        </div>
        <div className='group-send-block'>
          <h4>群发时间</h4>
          <div className='send-time'>
            <Radio.Group value={this.state.sendType} onChange={(e)=>{
              this.setState({
                sendType:e.target.value 
              })
            }} disabled>
              <Radio value={'now'}>立即发送</Radio>
              <Radio value={'time'}>定时发送</Radio>
            </Radio.Group>
            
            { this.state.sendType == 'time' && <div><TimePicker></TimePicker></div> }
            
          </div>
        </div>
        {/* <Button onClick={this.sendTransmit} type="primary" size="small" style={{ margin: '10px 0' }}>
          群发
        </Button> */}

        
      </div>
    );
  }
}
//export default WithSettingDetailHead('群发消息', MesGroupSend)
export default React.forwardRef((props:IMesGroupSendProps, ref) => {
  const mesGroupSendRef = React.useRef<MesGroupSend>(null);
  React.useImperativeHandle(ref, () => ({
    submit() {
      if( mesGroupSendRef.current ){
        mesGroupSendRef.current.sendTransmit(); // 调用类组件中的方法
      }
      
    },
    // 你可以在这里暴露其他方法或属性
  }));
  
  return <MesGroupSend visible={props.visible} ref={mesGroupSendRef} { ...props}/>
});
